package com.ikun.kunpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        //转为multipartFile
        MultipartFile multipartFile = (MultipartFile) inputSource;
        //定义文件的大小和允许的格式
        // 2MB
        final long MAX_MEMORY = 2 * 1024 * 1024L;
        // 允许的文件格式
        final List<String> ALLOW_TYPE = Arrays.asList("jpg", "png", "webp", "jpeg");
        // 校验
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件为空");

        // 1. 校验文件大小
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > MAX_MEMORY, ErrorCode.PARAMS_ERROR, "文件过大,不能超过2MB");

        // 2. 校验文件格式
        String originalFilename = multipartFile.getOriginalFilename();
        // 获得文件后缀名，扩展名不带“.”
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!ALLOW_TYPE.contains(suffix), ErrorCode.PARAMS_ERROR, "文件格式不支持");
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
